import React, {Component} from 'react';
import './index.less';
import {connect} from 'src/hrpub/common/store';
// 引入 ECharts 主模块
import echarts from 'echarts/lib/echarts';
import {isBlackBg} from 'src/hrpub/common/utils/utils';
// 引入柱状图
import 'echarts/lib/chart/bar';
// 引入提示框和标题组件
import 'echarts/lib/component/tooltip';
import {COMMON} from "../../../../unit/util";

class Echarts extends Component {
    constructor(props) {
        super(props);
        this.state = {};
    }

    componentWillReceiveProps(nextProps, nextContext) {
        if (nextProps.pk_org !== this.props.pk_org || nextProps.pk_psncl !== this.props.pk_psncl) {
            this.getChartData(nextProps);
        }
    }

    componentDidMount() {
        setTimeout(this.drawChart, 100)
    }

    drawChart = () => {
        // 基于准备好的dom，初始化echarts实例
        this.rankChart = echarts.init(document.getElementById('rank'));
        //  请求数据后 在初始化chart
        this.getChartData(this.props);
    };

    /**
     * 获取图表数据
     * @returns {Promise<void>}
     */
    getChartData = async (props) => {
        let postData = {
            pk_org: props.pk_org,
            pk_psncl: props.pk_psncl
        };
        let res = await props.dispatch({
            type: 'staffCom/queryJobGradeEchart',
            payload: {
                postData
            }
        });
        if (!res.success) return;
        this.formatData(res);
    };

    /**
     * 处理返回数据
     * @param res
     */
    formatData = (res) => {
        let xData = [];
        let yData = [];
        let shadows = [];
        let maxValue = 0;
        let length = 0;
        res.data.forEach(function (item) {
            xData.push(item.jobrankname);
            yData.push(item.cnt);
            length++;
            maxValue = item.cnt <= maxValue ? maxValue : item.cnt;
        });
        if (maxValue == 0) {
            maxValue = 1;
        }
        for (let i = 0; i < length; i++) {
            shadows.push(maxValue);
        }
        let option = this.getOptions(xData, yData, shadows);
        // 绘制图表
        this.rankChart.setOption(option);
    }


    getOptions(xData, yData, shadows) {
        let language = this.props.staffCom.language;
        let _this = this;
        let lineColor = isBlackBg() ? "#39393f" : "#ccc";
        return {
            title: {
                text: null
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                },
                formatter: function (params, ticket, callback) {
                    let name = '',
                        data = '';
                    params.forEach(function (o, i) {
                        if (i === 0) {
                            name = xData[o.dataIndex];
                            data = o.data;
                        }
                    });
                    return `${language['gx6008-000163']} ${name}<br />${language['gx6008-000137']}: ${data}`;
                }//`${info.grade}: {b}<br />${info.people_count}: {c}` // @1: 显示元素
            },
            legend: {
                textStyle: {
                    color: "#999"
                }
            },
            grid: {
                left: '3%',
                right: '3%',
                bottom: '8%',
                containLabel: true
            },
            xAxis: {
                //data: ["P5以下", "P6", "P7", "P8/M1", "P9/M2", "P10/M3", "M4"], // @2：x轴数据
                data: (function () {
                    let dd = xData.map(function (o) {
                        if (_this.getByteLen(o) > 8) {
                            return _this.sliceText(o);
                        } else {
                            return o;
                        }
                    });
                    return dd;
                })(),
                type: 'category',
                splitLine: {
                    show: false
                },
                axisLine: {
                    show: true,
                    lineStyle: {
                        color: lineColor
                    }
                },
                axisTick: {
                    show: false
                },
                axisLabel: {
                    interval: 0,
                    textStyle: {
                        color: '#999'
                    },
                    rotate: (function () {
                        let rtt = 0;
                        let hasLong = xData.map(function (o, i) {
                            if (_this.getByteLen(o) > 6) {
                                return true;
                            }
                        });
                        if (hasLong.length) {
                            rtt = -45;
                        }
                        return rtt;
                    })()
                }
            },
            yAxis: {
                type: 'value',
                // boundaryGap: [0, 0.01],
                splitLine: {
                    show: false
                },
                axisLine: {
                    show: true,
                    lineStyle: {
                        color: lineColor
                    }
                },
                axisTick: {
                    show: false
                },
                axisLabel: {
                    textStyle: {
                        color: '#999'
                    }
                }
            },
            series: [{
                name: language['gx6008-000137'], //@3: y轴显示
                type: 'bar',
                //data: [192, 168, 141, 194, 84, 201, 143], // @4: 主数据
                data: yData,
                barMaxWidth: 40,
                itemStyle: {
                    normal: {
                        color: '#82a9ed',
                        label: {
                            show: true,
                            position: 'top',
                            textStyle: {
                                color: '#666'
                            }
                        }
                    }
                }
            }, { // For shadow
                type: 'bar',
                itemStyle: {
                    normal: {color: 'rgba(0,0,0,0.05)'}
                },
                barMaxWidth: 40,
                barGap: '-100%',
                barCategoryGap: '40%',
                //data: [250, 250, 250, 250, 250, 250, 250],
                data: shadows,
                animation: false
            }]
        };
    }

    getByteLen(val) {
        let len = 0;
        if (val !== undefined) {
            for (let i = 0; i < val.length; i++) {
                let patt = new RegExp(/[^\x00-\xff]/ig);
                let a = val[i];
                if (patt.test(a)) {
                    len += 2;
                } else {
                    len += 1;
                }
            }
        }
        return len;
    }

    sliceText(val) {
        let len = 0,
            _index = 0;
        for (let i = 0; i < val.length; i++) {
            let patt = new RegExp(/[^\x00-\xff]/ig);
            let a = val[i];
            if (patt.test(a)) {
                len += 2;
            } else {
                len += 1;
            }
            if (len >= 6) {
                _index = i + 1;
                break;
            }
        }

        return val.slice(0, _index) + '...';
    }

    render() {
        const {staffCom} = this.props;
        return (
            <div className={'rank-structure'}>
                <div className={`chart-title  ${this.props.titleClass}`}>
                    <div className={`title-name`}>
                        {staffCom.language["gx6008-000182"]}
                    </div>
                    <div className={'more'} onClick={() => {
                        this.props.showDetail(COMMON.pageRankStr)
                    }}>
                    </div>
                </div>
                <div className={"chart-content"} id={"rank"}>

                </div>
            </div>
        );
    }
}

export default Echarts;
